<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>鼠标跟随</title>
  <style>
    * { padding: 0; margin: 0; }
    html,body { height: 100%;}
    #app {
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <div id="app">
    鼠标的位置为：({{ position.x }}, {{ position.y }})
  </div>
</body>
<script src="../lib/vue.global.js"></script>
<script>

  const { reactive, onMounted, onUnmounted } = Vue

  function useMouse () {
    const position = reactive({
        x: 0, y: 0
    })

    const updatePosition = (event) => {
      position.x = event.pageX
      position.y = event.pageY
    }

    onMounted(() => {
      document.addEventListener('mousemove', updatePosition, false)
    })
    
    onUnmounted(() => {
      document.removeEventListener('mousemove', updatePosition, false)
    })

    return position
  }

  Vue.createApp({
    setup () {
      const position = useMouse()

      return {
        position
      }
    }
  }).mount('#app')
</script>
</html>